const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const fileCache = require('./services/fileCache');
require('dotenv').config();

const {
  generateProgrammingCard,
  generatePoemCard,
  generateCareerCard,
  generateHistoryCard,
  generateScienceCard,
  generateMBTITestCard,
  generateCareerMatchCard,
  HISTORY_CATEGORIES
} = require('./services/cardGenerators');

const app = express();

// Middleware
app.use(cors());
app.use(helmet({
  contentSecurityPolicy: {
    directives: {
      defaultSrc: ["'self'"],
      styleSrc: ["'self'", "'unsafe-inline'"],
      scriptSrc: ["'self'", "'unsafe-inline'"],
      imgSrc: ["'self'", "data:", "https:"],
      connectSrc: ["'self'", process.env.QIANWEN_API_URL]
    }
  }
}));
app.use(morgan('dev'));
app.use(bodyParser.json());

// 设置缓存清理定时任务
const cleanupInterval = 60 * 60 * 1000; // 每小时检查一次
setInterval(() => {
  const now = new Date();
  if (now.getHours() === 2 && now.getMinutes() === 0) { // 每天凌晨2点执行清理
    console.log('开始执行缓存清理任务...');
    fileCache.cleanupCache()
      .then(() => console.log('缓存清理任务完成'))
      .catch(err => console.error('缓存清理任务失败:', err));
  }
}, cleanupInterval);

// 获取缓存统计信息
app.get('/api/cache/stats', async (req, res) => {
  try {
    const stats = await fileCache.getStats();
    res.json({
      success: true,
      data: stats
    });
  } catch (error) {
    console.error('获取缓存统计信息失败:', error);
    res.status(500).json({
      success: false,
      error: '获取缓存统计信息失败'
    });
  }
});

// 手动清理缓存
app.post('/api/cache/cleanup', async (req, res) => {
  try {
    await fileCache.cleanupCache();
    const stats = await fileCache.getStats();
    res.json({
      success: true,
      message: '缓存清理完成',
      data: stats
    });
  } catch (error) {
    console.error('手动清理缓存失败:', error);
    res.status(500).json({
      success: false,
      error: '清理缓存失败'
    });
  }
});

// Routes
app.post('/api/generate-card', async (req, res) => {
  try {
    const { cardType, parameters } = req.body;
    
    // 基本参数验证
    if (!cardType || !parameters) {
      throw new Error('Invalid request parameters');
    }

    // 根据卡片类型验证必要参数
    if (cardType === 'history') {
      if (!parameters.category) {
        throw new Error('历史卡片需要提供 category 参数');
      }
    } else {
      if (!parameters.query) {
        throw new Error('需要提供 query 参数');
      }
    }

    let result;
    switch (cardType) {
      case 'programming':
        result = await generateProgrammingCard(parameters);
        break;
      case 'poem':
        result = await generatePoemCard(parameters);
        break;
      case 'career':
        result = await generateCareerCard(parameters);
        break;
      case 'history':
        result = await generateHistoryCard(parameters);
        break;
      case 'science':
        result = await generateScienceCard(parameters);
        break;
      default:
        throw new Error('Invalid card type');
    }

    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    console.error('Error generating card:', error);
    res.status(500).json({
      success: false,
      error: error.message || '生成卡片失败，请稍后重试'
    });
  }
});

// MBTI测试相关路由
app.post('/api/mbti-test', async (req, res) => {
  try {
    const { sessionId, questionNumber, answer, action = 'continue' } = req.body;
    
    if (!sessionId) {
      throw new Error('需要提供sessionId');
    }

    const result = await generateMBTITestCard({
      sessionId,
      questionNumber,
      answer,
      action
    });

    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    console.error('MBTI测试处理失败:', error);
    res.status(500).json({
      success: false,
      error: error.message || 'MBTI测试处理失败'
    });
  }
});

// 职业匹配分析路由
app.post('/api/career-match', async (req, res) => {
  try {
    console.log('收到职业匹配分析请求:', req.body);
    const { mbtiType, careerPreferences } = req.body;
    
    if (!mbtiType) {
      console.error('缺少MBTI类型参数');
      throw new Error('需要提供MBTI类型');
    }

    console.log('开始生成职业匹配分析，MBTI类型:', mbtiType);
    const result = await generateCareerMatchCard({
      mbtiType,
      careerPreferences
    });
    console.log('生成职业匹配分析结果:', result);

    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    console.error('职业匹配分析失败:', error);
    res.status(500).json({
      success: false,
      error: error.message || '职业匹配分析失败'
    });
  }
});

// Error handling middleware
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({
    success: false,
    error: 'Internal server error'
  });
});

const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
}); 